/**
 * by 菲鸽 on 2024-03-06
 * 路由拦截，通常也是登录拦截
 * 可以设置路由白名单，或者黑名单，看业务需要选哪一个
 * 我这里应为大部分都可以随便进入，所以使用黑名单
 */
import {useAppStore, useLoginStore, usePmDictStore, useUserStore} from '@/stores'
import {getLastPage, currRoute, queryToUrl} from '@/utils'
import {PM_ROUTE_PATH, usePmAppStore} from "@/stores/pm";
import {useRouteHistoryStore} from "@/stores/routeHistory";

// TODO Check
const loginRoute = import.meta.env.VITE_LOGIN_URL

const isLogined = () => {
  return !!useLoginStore().getToken()
}

const isDev = import.meta.env.DEV

const whiteList = ['/pages/login/index', '/pmPages/login/index']
const OaSocialLoginUrl = '/oaPages/login/index';
const PmSocialLoginUrl = '/pmPages/login/index';
const h5PasskeyUrl = 'http://hxpm.huaxinservice.com:1101/passkey/#/passport/login'


export function gotoH5PasskeyLogin(url?: string) {
  const route = currRoute()
  const path = queryToUrl(route.path, route.query)
  usePmAppStore().setLoginRedirectUrl(path);
  // #ifdef H5
  window.open(h5PasskeyUrl, '_self');
  // #endif
  // #ifndef H5
  const redirectRoute = `${loginRoute}?redirect=${encodeURIComponent(url)}`
  uni.navigateTo({ url: redirectRoute })
  // #endif
}

// 黑名单登录拦截器 - （适用于大部分页面不需要登录，少部分页面需要登录）
export const navigateToInterceptor = {
  // 注意，这里的url是 '/' 开头的，如 '/pages/index/index'，跟 'pages.json' 里面的 path 不同
  // 增加对相对路径的处理，BY 网友 @ideal
  invoke({ url }: { url: string }) {
    const route = currRoute()
    useRouteHistoryStore().routeHistoryAdd(route.path, route.query);
    useAppStore().setShowGLoading(true)
    const currentUrl = url || '/'
    let path = currentUrl.split('?')[0]

    // 处理相对路径
    if (!path.startsWith('/')) {
      const currentPath = getLastPage()?.route || ''
      const normalizedCurrentPath = currentPath.startsWith('/') ? currentPath : `/${currentPath}`
      const baseDir = normalizedCurrentPath.substring(0, normalizedCurrentPath.lastIndexOf('/'))
      path = `${baseDir}/${path}`
    }

    if (whiteList.includes(path)) {
      return true
    }
    const hasLogin = true
    if (hasLogin) {
      if (path === '/' || path === '/pages/index/index') {
        usePmAppStore().clearUserInfo();
      }
      if (path.includes(PM_ROUTE_PATH)) {
        const pmToken = usePmAppStore().getToken()
        if (pmToken) {
          if (usePmAppStore().userInfo.roles.length === 0) {
            usePmAppStore().getInfo().then()
          }
          if (!usePmDictStore().dictData) {
            usePmDictStore().loadDictData().then()
          }
          return true;
        } else if (path === PmSocialLoginUrl) {
          return true;
        }
        usePmAppStore().getPasskeyAuthCode(path);
        return false
      } else {
        return true
      }
    }
    gotoH5PasskeyLogin(url);
    return false
  },
  complete() {
    useAppStore().setShowGLoading(false)
  }
}

export const routeInterceptor = {
  install() {
    uni.addInterceptor('navigateTo', navigateToInterceptor)
    uni.addInterceptor('reLaunch', navigateToInterceptor)
    uni.addInterceptor('redirectTo', navigateToInterceptor)
    uni.addInterceptor('switchTab', navigateToInterceptor)
    uni.addInterceptor('navigateBack', navigateToInterceptor)
  },
}
